package com.training.api.service;

import com.training.api.repository.ClientPublicKeyRepository;
import com.training.bean.ClientPublicKey;
import com.training.utils.AESUtil;
import com.training.utils.RSAUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.crypto.SecretKey;
import java.security.PublicKey;
import java.util.Date;
import java.util.Optional;

@Service
public class ClientKeyService {
    
    @Autowired
    private ClientPublicKeyRepository clientPublicKeyRepository;
    // 从配置文件中获取音频加密密钥
    @Value("${audio.encryption.key}")
    private String audioEncryptionKey;
    /**
     * 保存客户端公钥
     * @param uid 用户ID
     * @param publicKeyStr Base64编码的公钥字符串
     * @return 保存的公钥对象
     */
    public ClientPublicKey saveClientPublicKey(int uid, String publicKeyStr) {
        // 检查是否已存在该客户端的公钥
        Optional<ClientPublicKey> existingKey = clientPublicKeyRepository.findByUid(uid);
        
        ClientPublicKey clientPublicKey;
        if (existingKey.isPresent()) {
            // 更新现有公钥
            clientPublicKey = existingKey.get();
            clientPublicKey.setPublicKey(publicKeyStr);
            clientPublicKey.setUpdateDate(new Date());
        } else {
            // 创建新的公钥记录
            clientPublicKey = new ClientPublicKey();
            clientPublicKey.setUid(uid);
            clientPublicKey.setPublicKey(publicKeyStr);
            clientPublicKey.setCreateDate(new Date());
            clientPublicKey.setUpdateDate(new Date());
        }
        
        return clientPublicKeyRepository.save(clientPublicKey);
    }
    
    /**
     * 获取客户端公钥
     * @param clientId 客户端ID
     * @return 公钥对象，如果不存在则返回null
     */
    public PublicKey getClientPublicKey(int clientId) throws Exception {
        Optional<ClientPublicKey> clientPublicKey = clientPublicKeyRepository.findByUid(clientId);
        if (clientPublicKey.isPresent()) {
            return RSAUtil.loadPublicKey(clientPublicKey.get().getPublicKey());
        }
        return null;
    }
    
    /**
     * 使用客户端公钥加密AES密钥
     * @param clientId 客户端ID
     * @param aesKey AES密钥
     * @return 加密后的AES密钥（Base64编码）
     * @throws Exception 加密异常
     */
    public String encryptAESKeyForClient(int clientId, SecretKey aesKey) throws Exception {
        PublicKey publicKey = getClientPublicKey(clientId);
        if (publicKey == null) {
            throw new Exception("客户端公钥不存在");
        }
        return RSAUtil.encryptAESKey(aesKey, publicKey);
    }
    
    /**
     * 使用客户端公钥加密AES密钥字符串
     * @param clientId 客户端ID
     * @param aesKeyStr AES密钥字符串
     * @return 加密后的AES密钥（Base64编码）
     * @throws Exception 加密异常
     */
    public String encryptAESKeyForClient(int clientId, String aesKeyStr) throws Exception {
        PublicKey publicKey = getClientPublicKey(clientId);
        if (publicKey == null) {
            throw new Exception("客户端公钥不存在");
        }
        return RSAUtil.encryptAESKey(aesKeyStr, publicKey);
    }
    
    /**
     * 为客户端生成并加密AES密钥
     * @param clientId 客户端ID
     * @return 加密后的AES密钥（Base64编码）
     * @throws Exception 异常
     */
    public String generateAndEncryptAESKey(int clientId) throws Exception {
        // 使用客户端公钥加密AES密钥
        return encryptAESKeyForClient(clientId, audioEncryptionKey);
    }
}